package com.um.jdy.platform.shop.manager;

import cn.hutool.core.bean.BeanUtil;
import com.um.jdy.common.shop.entity.po.Courier;
import com.um.jdy.common.shop.service.CourierService;
import com.um.jdy.common.commons.utils.Kuaidi100Util;
import com.um.jdy.common.market.service.ActivityGoodsOptionService;
import com.um.jdy.common.member.entity.po.MemberUser;
import com.um.jdy.common.member.service.MemberUserService;
import com.um.jdy.common.shop.code.ShopOrderCode;
import com.um.jdy.common.shop.entity.po.Order;
import com.um.jdy.common.shop.entity.dto.OrderDTO;
import com.um.jdy.common.shop.entity.po.OrderGoods;
import com.um.jdy.common.shop.entity.vo.OrderVO;
import com.um.jdy.common.shop.enums.OrderEnum;
import com.um.jdy.common.shop.service.GoodsOptionService;
import com.um.jdy.common.shop.service.OrderGoodsService;
import com.um.jdy.common.shop.service.ShopOrderService;
import com.um.jdy.platform.shop.entity.dto.DeliveryDTO;
import com.um.jdy.platform.shop.entity.vo.OrderSummaryVO;
import com.um.jdy.platform.shop.entity.vo.ShopOrderDetailVO;
import com.um.jdy.platform.shop.entity.vo.ShopOrderExportVO;
import com.um.jdy.platform.shop.entity.vo.ShopOrderItemVO;
import com.um.springboot.starter.dao.CommonDao;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BasePlusManager;
import com.um.springboot.starter.orm.params.ExportParams;
import com.um.springboot.starter.orm.params.ListDTO;
import com.um.springboot.starter.orm.params.PageDTO;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.DateUtil;
import com.um.springboot.starter.utils.ExcelUtil;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 管理类：订单表
 */
@Component
public class ShopOrderManager extends BasePlusManager<ShopOrderService, Order, OrderDTO, OrderVO, PageDTO, ListDTO> {

    @Autowired
    OrderGoodsService orderGoodsService;

    @Autowired
    MemberUserService memberUserService;

    @Autowired
    GoodsOptionService goodsOptionService;

    @Autowired
    ActivityGoodsOptionService activityGoodsOptionService;

    @Autowired
    CourierService courierService;

    @Autowired
    CommonDao commonDao;


    public Page<ShopOrderItemVO> getPage(PageParams pageParams) {

        Page<ShopOrderItemVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());

        pageParams.getCondition().put("s.com_id", getComId());

        page = service.getCMSViewModelPageBySqlName(page, "shop_get_order_page", "shop_get_order_count",
                ShopOrderItemVO.class, pageParams.getProperties(), pageParams.getValues(),
                pageParams.getRangeEntitys(), pageParams.getOrderNames(), pageParams.getSortOns());

        page.getResult().stream().forEach(item -> {
            List goodsList = orderGoodsService.getList("shop_order_id",item.getShopOrderId());
            item.setGoods(goodsList);
        });


        OrderSummaryVO extraDataVO = service.getCMSViewModelBySqlName("shop_get_order_summary",OrderSummaryVO.class, pageParams.getProperties(), pageParams.getValues(),
                pageParams.getRangeEntitys());
        long unpaidCount = service.getCountBySqlName("shop_get_order_status_count",new Object[]{getComId(),OrderEnum.Status.UnPay.name()});
        long undeliveryCount = service.getCountBySqlName("shop_get_order_status_count",new Object[]{getComId(),OrderEnum.Status.UnSend.name()});
        long unreceivingCount = service.getCountBySqlName("shop_get_order_status_count",new Object[]{getComId(),OrderEnum.Status.UnReceive.name()});
        long unevaluatedCount = service.getCountBySqlName("shop_get_order_status_count",new Object[]{getComId(),OrderEnum.Status.UnComment.name()});

        extraDataVO.setUnpaidCount(unpaidCount);
        extraDataVO.setUndeliveryCount(undeliveryCount);
        extraDataVO.setUnreceivingCount(unreceivingCount);
        extraDataVO.setUnevaluatedCount(unevaluatedCount);

        page.setExtraData(extraDataVO);


        return page;
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public ShopOrderDetailVO getOrderDetail(String id){
        Order shopOrder = service.getEntity(id);
        if(shopOrder == null){
            throw new ServiceException(ShopOrderCode.OrderNoExist);
        }

        List<OrderGoods> orderGoodsList = orderGoodsService.getList("shop_order_id",id,"create_time","asc");
        MemberUser memberUser = memberUserService.getEntity(shopOrder.getMemberUserId());

        ShopOrderDetailVO orderDetailVO = UMBeanUtils.copyBean(shopOrder,ShopOrderDetailVO.class);
        orderDetailVO.setGoods(orderGoodsList);

        if(memberUser != null){
            orderDetailVO.setNickname(memberUser.getNickname());
            orderDetailVO.setPhoto(memberUser.getPhoto());
        }

        return orderDetailVO;
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    public Response cancel(String id){
        Order shopOrder = service.getEntity(id);
        if(shopOrder == null){
            throw new ServiceException(ShopOrderCode.OrderNoExist);
        }

        if(!StringUtil.equals(shopOrder.getStatus(), OrderEnum.Status.UnPay.name())){
            throw new ServiceException(ShopOrderCode.CancelFailureForPayed);
        }

        shopOrder.setStatus(OrderEnum.Status.Cancelled.name());

        List<OrderGoods> orderGoodsList = orderGoodsService.getList("shop_order_id",shopOrder.getShopOrderId());
        orderGoodsList.stream().forEach(item -> {
            goodsOptionService.addStock(item.getShopGoodsOptionId(),item.getNum());

            //如果是活动商品退活动库存
            if(!StringUtil.isEmpty(item.getMarketActivityId())){
                goodsOptionService.addActivityStock(item.getMarketActivityGoodsOptionId(),item.getNum());
            }
        });

        service.update(shopOrder);
        return Response.success();
    }

    /**
     * 发货
     * @param dto
     * @return
     */
    public Response delivery(DeliveryDTO dto){
        Order order = service.getEntity(dto.getOrderId());
        if(order == null){
            throw new ServiceException(ShopOrderCode.OrderNoExist);
        }

        if(StringUtil.isEmpty(order.getCourierNo())) {
            if (!StringUtil.equals(order.getStatus(), OrderEnum.Status.UnSend.name())) {
                throw new ServiceException(ShopOrderCode.OrderIsNotUnSend);
            }
        }else{
            if (!(StringUtil.equals(order.getStatus(), OrderEnum.Status.UnReceive.name()) || StringUtil.equals(order.getStatus(), OrderEnum.Status.UnSend.name()))) {
                throw new ServiceException(ShopOrderCode.OrderStatusIsUnSendOrUnReceive);
            }
        }

        Order newOrder = new Order();
        newOrder.setShopOrderId(order.getShopOrderId());

        newOrder.setCourier(dto.getExpress());
        newOrder.setCourierNo(dto.getExpressNo());

        newOrder.setStatus(OrderEnum.Status.UnReceive.name());
        newOrder.setDeliveryTime(new Date());

        //生成用户订单动态 TODO 暂时不推送
//        List<Map> orderGoodsList = dao.queryList(TableName.MALL_ORDER_GOODS,new String[]{"mall_order_id"},new Object[]{order.get("mall_order_id")});
//        String goodsName = StringUtil.getTrim(orderGoodsList.get(0).get("goods_name"));
//        if(orderGoodsList.size() > 1){
//            goodsName = goodsName+"等"+orderGoodsList.size()+"件商品";
//        }

        service.update(newOrder);

        return Response.success();
    }

    /**
     * 导出订单
     * @param exportParams
     * @return
     */
    public Response exportShopOrderPage(ExportParams exportParams) {
        exportParams.getCondition().put("s.com_id", getComId());

        List<ShopOrderItemVO> list = service.getCMSViewModelListBySqlName("shop_get_order_page", ShopOrderItemVO.class, exportParams.getProperties(), exportParams.getValues(), exportParams.getRangeEntitys(),
                exportParams.getOrderNames(), exportParams.getSortOns(), new Object[]{exportParams.getStart(), exportParams.getLimit()});

        List<ShopOrderExportVO> shopOrderExportList = BeanUtil.copyToList(list, ShopOrderExportVO.class);

        shopOrderExportList.forEach(item -> {
            String skuCode = "";
            String goodsInfo = "";

            List<OrderGoods> goodsList = orderGoodsService.getList("shop_order_id",item.getShopOrderId());

            for (int index = 0; index < goodsList.size(); index++) {
                OrderGoods orderGoods = goodsList.get(index);
                goodsInfo += "商品名称:"+ orderGoods.getGoodsName() +"  ";
                goodsInfo += "商品单价:"+ orderGoods.getGoodsPrice() / 100.0 +"  ";
                goodsInfo += "购买数量:"+ orderGoods.getNum() +"  ";
                goodsInfo += "购买规格:"+ orderGoods.getSpec() +"  ";
                if(orderGoods.getSkuCode() == null) {
                    skuCode += ":" + orderGoods.getNum();
                }else {
                    skuCode += (orderGoods.getSkuCode() + ":" + orderGoods.getNum());
                }

                if(index + 1 < goodsList.size()){
                    skuCode += "/";
                }

            }
            item.setSkuCode(skuCode);
            item.setGoodsInfo(goodsInfo);

            String receiveInfo = "收件人："+ item.getLinkman() +"  ";
            receiveInfo += "联系电话："+ item.getPhone() +"  ";
            receiveInfo += "收件地址："+ item.getProvince() + item.getCity() + item.getArea() + item.getAddress() +"  ";
            item.setReceiveInfo(receiveInfo);


            if(OrderEnum.Status.valueOf(item.getStatus()) != null) {
                item.setStatusText(OrderEnum.Status.valueOf(item.getStatus()).getValue());
            }else{
                item.setStatusText("未知");
            }

        });

        Map mapFormat = new Hashtable();
        mapFormat.put("create_time","yyyy-MM-dd HH:mm:ss");
        mapFormat.put("payment","number");
        mapFormat.put("price","number");

        String fileName = "Excel" + DateUtil.getDateString(new Date(), "yyyyMMddHHmmss") + ".xls";
        String path = service.getExportFilePath(fileName);
        List<String> columns = Arrays.asList("订单号","收件人","省","市","区（县）","收件人地址","手机","客户备注","购买时间","订单金额","会员用户名", "订单状态","商品信息","SKU代码");
        List<String> properties = Arrays.asList("order_no","linkman","province","city","area","address","phone","remark","create_time","payment","user_nickname", "status_text","goods_info","sku_code");
        ExcelUtil.writeEntity(path, columns, shopOrderExportList, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(), true);
        return Response.success(service.getDownFilePath(fileName));
    }


    /**
     * 查询物流轨迹
     *
     * @param shopOrderId
     * @return
     */
    public Object getExpressTrack(String shopOrderId) {
        Order order = service.getEntity(shopOrderId);
        Courier courier = courierService.getEntity("name", order.getCourier());
        Object expressTrack = Kuaidi100Util.queryTrack(Optional.ofNullable(courier).orElseGet(Courier::new).getCode(),
                order.getCourierNo(), order.getPhone());
        return expressTrack;
    }

}
